Remove Nth Node From End of List

Given a linked list, remove the nth node from the end of list and return its head.

For example,

  1. Given linked list: 1->2->3->4->5, and n = 2.
  2. After removing the second node from the end, the linked list becomes 1->2->3->5.

Note:

Given n will always be valid.

Try to do this in one pass.

Solution:

  1. /**
  2. * Definition for singly-linked list.
  3. * public class ListNode {
  4. * int val;
  5. * ListNode next;
  6. * ListNode(int x) { val = x; }
  7. * }
  8. */
  9. public class Solution {
  10. public ListNode removeNthFromEnd(ListNode head, int n) {
  11. ListNode slow = head, fast = head;
  12. while (n-- > 0)
  13. fast = fast.next;
  14. if (fast == null)
  15. return head.next;
  16. while (fast != null && fast.next != null) {
  17. slow = slow.next;
  18. fast = fast.next;
  19. }
  20. slow.next = slow.next.next;
  21. return head;
  22. }
  23. }